package baibeiwallet.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alm.token.R;
import com.alm.token.base.BaseActivity;
import com.alm.token.ui.persenter.MyPreenter;
import com.alm.token.utils.ActionBarHelper;
import com.alm.token.utils.CommonUtil;

import org.web3j.crypto.CipherException;
import org.web3j.crypto.ECKeyPair;
import org.web3j.crypto.Keys;
import org.web3j.crypto.Wallet;
import org.web3j.utils.Numeric;

import baibeiwallet.BaibeiWallet;
import baibeiwallet.ClipboardUtils;
import baibeiwallet.WalletDaoUtils;
import baibeiwallet.WalletManager;
import baibeiwallet.WalletUtils;
import baibeiwallet.model.ETHWallet3;
import baibeiwallet.utils.DialogUtils;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class WalletSettingActivity1 extends BaseActivity {
    @BindView(R.id.leftItem)
    ImageView leftItem;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.tv_export_data)
    TextView mTvExprotData;
    @BindView(R.id.tv_address)
    TextView mTvAddress;
    BaibeiWallet mWallet;

    public static final int ITEM_walletname = 1, ITEM_beifenmonic = 2, ITEM_expprivkey = 3, ITEM_expkeystore = 4, ITEM_clearwallet = 5;
    public int itemNum = 0;
    @BindView(R.id.btn_export)
    Button btnExport;
    @BindView(R.id.tv_daochushow)
    TextView mTvDaochushow;
    @BindView(R.id.et_walletpwd)
    EditText mEtWalletPwd;

    private int exportType = 0;

    @Override
    protected MyPreenter initPreenter() {
        return null;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_wallet_setting3;
    }

    @Override
    protected void initVariables() {
        int index = getIntent().getIntExtra("index", 0);
        mWallet = WalletManager.getInstance().getWallet(index);
        itemNum = getIntent().getIntExtra("itemNum", 0);
    }

    @Override
    protected void initViews() {
        String title = getString(R.string.title_hint_item22);
        switch (itemNum) {
            case ITEM_walletname:
                title = getString(R.string.title_hint_item23);
                break;
            case ITEM_beifenmonic:
                title = getString(R.string.title_hint_item24);
                mTvDaochushow.setText(getString(R.string.wallet_import_hint13));
                exportType = 1;

                break;
            case ITEM_expprivkey:
                title = getString(R.string.title_hint_item25);
                mTvDaochushow.setText(getString(R.string.wallet_import_hint14));
                exportType = 2;


                break;
            case ITEM_expkeystore:
                title = getString(R.string.title_hint_item26);
                mTvDaochushow.setText(getString(R.string.wallet_import_hint15));
                exportType = 3;

                break;
            case ITEM_clearwallet:
                title = getString(R.string.title_hint_item27);
                break;
        }
        new ActionBarHelper(this).setTitle(title);

        mTvName.setText(mWallet.getWalletName().indexOf("wallet") != -1 ? mWallet.getWalletName() : mWallet.getWalletName() + " wallet");

        address = Keys.toChecksumAddress(mWallet.getWalletFile().getAddress());
        String str1 = "", str2 = "";
        if (!address.isEmpty()) {
            int length = address.length();
            str1 = address.substring(0, length % 2 == 0 ? length / 2 : (length - 1) / 2);
            str2 = address.substring((length % 2 == 0 ? length / 2 : (length - 1) / 2) + 1);
        }
        mTvAddress.setText(str1 + "\n" + str2);
//        mTvAddress.setText(address);
    }

    @Override
    protected void loadData() {

    }

    String address = "";

    @OnClick(R.id.tv_address)
    public void onClickCopyAddress() {
        if (TextUtils.isEmpty(address)) {
            showToast(getString(R.string.wallet_hint_warn5));
//            Toast.makeText(this, "地址为空", Toast.LENGTH_SHORT).show();
            return;
        }

        ClipboardUtils.copy(address);
    }
    /**
     * 隐藏软键盘
     */
    public void hideKeyboard() {
        if (this.getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
            if (this.getCurrentFocus() != null) {
                InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    @OnClick(R.id.btn_export)
    public void onClickExportMnemonic() {
        if (btnExport.getText().toString().equalsIgnoreCase(getString(R.string.wallet_hint_export))) {

            if (mWallet == null) {
                showToast(getString(R.string.wallet_import_hint17));
//            Toast.makeText(this, "暂时没有导入钱包", Toast.LENGTH_SHORT).show();
                return;
            }

//        DialogUtils.enterPwd(WalletSettingActivity1.this, (pwd) -> {
            String pwd = mEtWalletPwd.getText().toString();
            if (!checkPwd(pwd)) {
                return;
            }
            btnExport.setText(getString(R.string.wallet_import_hint18));
            long startTime = System.currentTimeMillis();

            switch (exportType) {
                case 1:
//                    Toast.makeText(this, "开始导出，请稍等。。。", Toast.LENGTH_SHORT).show();



//        DialogUtils.enterPwd(WalletSettingActivity1.this, (pwd) -> {

                    Log.i("TAG", "onClickExportMnemonic: 助记词 = " + mWallet.getMnemonic());

                    long timeSpace = System.currentTimeMillis() - startTime;
                    Log.i("TAG", "onClickExportMnemonic: 校验密码之前 = " + timeSpace);

                    if (!WalletUtils.checkPwd(pwd, mWallet.getWalletFile())) {
                        Toast.makeText(this, getString(R.string.profile_hint_item29), Toast.LENGTH_SHORT).show();
                        btnExport.setText(getString(R.string.wallet_hint_export));
                        return;
                    }
                    timeSpace = System.currentTimeMillis() - startTime;
                    Log.i("TAG", "onClickExportMnemonic: " + "总耗时 = " + timeSpace + ";助记词 = " + mWallet.getMnemonic());
                    if (TextUtils.isEmpty(mWallet.getMnemonic())) {
                        for (ETHWallet3 ethWallet : WalletDaoUtils.loadAll()) {
                            if (ethWallet.getAddress().equalsIgnoreCase(Keys.toChecksumAddress(mWallet.getWalletFile().getAddress()))) {
                                mTvExprotData.setText(ethWallet.getMnemonic());
                                hideKeyboard();
                                btnExport.setText(getString(R.string.wallet_import_hint19));
                                break;
                            }
                        }

                    } else {
                        mTvExprotData.setText(mWallet.getMnemonic());
                        hideKeyboard();
                        btnExport.setText(getString(R.string.wallet_import_hint19));
                    }
                    break;
                case 2:


//        DialogUtils.enterPwd(WalletSettingActivity1.this, (pwd) -> {

                    long timeSpace2 = System.currentTimeMillis() - startTime;
                    Log.i("TAG", "onClickExportMnemonic: 校验密码之前 = " + timeSpace2);

                    if (!WalletUtils.checkPwd(pwd, mWallet.getWalletFile())) {
                        Toast.makeText(this, getString(R.string.profile_hint_item29), Toast.LENGTH_SHORT).show();
                        btnExport.setText(getString(R.string.wallet_hint_export));
                        return;
                    }
                    timeSpace2 = System.currentTimeMillis() - startTime;
                    Log.i("TAG", "checkPwdAll: 总耗时 = " + timeSpace2);

                    try {
                        ECKeyPair ecKeyPair = Wallet.decrypt(pwd, mWallet.getWalletFile());
                        String privateKey = Numeric.toHexStringNoPrefix(ecKeyPair.getPrivateKey());
                        timeSpace2 = System.currentTimeMillis() - startTime;

                        Log.i("TAG", "总消耗时间 = " + timeSpace2 + ";私钥 = " + privateKey);
                        mTvExprotData.setText(privateKey);
                        hideKeyboard();
                        btnExport.setText(getString(R.string.wallet_import_hint20));
                    } catch (CipherException e) {
                        e.printStackTrace();
                        hideKeyboard();
                        btnExport.setText(getString(R.string.wallet_hint_export));
                    }
                    break;
                case 3:


//        DialogUtils.enterPwd(WalletSettingActivity1.this, (pwd) -> {

                    long timeSpace3 = System.currentTimeMillis() - startTime;
                    Log.i("TAG", "onClickExportMnemonic: 校验密码之前 = " + timeSpace3);

                    if (!WalletUtils.checkPwd(pwd, mWallet.getWalletFile())) {
                        Toast.makeText(this, getString(R.string.profile_hint_item29), Toast.LENGTH_SHORT).show();
                        btnExport.setText(getString(R.string.wallet_hint_export));
                        return;
                    }
                    timeSpace3 = System.currentTimeMillis() - startTime;
                    Log.i("TAG", "总消耗时间 = " + timeSpace3 + "keyStore = " + mWallet.getKeyStoreJsonString());
                    mTvExprotData.setText(mWallet.getKeyStoreJsonString());
                    hideKeyboard();
                    btnExport.setText(getString(R.string.wallet_import_hint21));
                    break;

            }
        } else if (btnExport.getText().toString().equalsIgnoreCase(getString(R.string.wallet_import_hint18))) {

        } else if (btnExport.getText().toString().indexOf(getString(R.string.wallet_import_hint22)) != -1) {
            onClickCopy();
        }


//            mTvExprotData.setText(mWallet.getMnemonic());
//        });
    }

    public void onClickCopy() {
        String result = mTvExprotData.getText().toString();
        if (TextUtils.isEmpty(result)) {
            showToast(getString(R.string.wallet_import_hint16));
//            Toast.makeText(this, "数据不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }
        ClipboardUtils.copy(result);
    }

    private boolean checkPwd(String pwd) {
        if (TextUtils.isEmpty(pwd)) {
            Toast.makeText(this, getString(R.string.wallet_hint_pleaseinputpsw), Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }


    @Override
    public void onClick(View v) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
